package com.sdr.hkcamera;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.hikvision.vmsnetsdk.CameraInfo;
import com.hikvision.vmsnetsdk.ControlUnitInfo;
import com.hikvision.vmsnetsdk.RegionInfo;
import com.sdr.hkcamera.data.Node;
import com.sdr.hkcamera.data.TempData;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by homelajiang on 2016/9/28 0028.
 */

public class ResourceListFragment extends Fragment {

    private RecyclerView recyclerView;
    private int _MARGIN = 20;
    private CameraCallback callback;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(getResources().getIdentifier("recyclerview","layout",getActivity().getPackageName()), container, false);
        root.findViewById(getResources().getIdentifier("btn_cancel","id",getActivity().getPackageName()))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Fragment temp = getActivity().getSupportFragmentManager().findFragmentByTag("list");
                        if (temp != null) {
                            getActivity().getSupportFragmentManager().beginTransaction().remove(temp).commit();
                        }
                    }
                });
        recyclerView = (RecyclerView) root.findViewById(getResources().getIdentifier("recyclerView","id",getActivity().getPackageName()));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        NodeAdapter adapter = new NodeAdapter(TempData.getInstance().getNodeList());
        recyclerView.setAdapter(adapter);
        adapter.setListener(new CameraClickListener() {
            @Override
            public void onCameraClick(CameraInfo info) {
                TempData.getInstance().setCameraInfo(info);
                if(callback!=null){
                    callback.clickCamera();
                }
                Fragment temp = getActivity().getSupportFragmentManager().findFragmentByTag("list");
                if (temp != null) {
                    getActivity().getSupportFragmentManager().beginTransaction().remove(temp).commit();
                }
            }
        });
        return root;
    }


    public void setCameraClickCallback(CameraCallback callback){
        this.callback = callback;
    }
    class NodeAdapter extends RecyclerView.Adapter<NodeAdapter.NodeHolder> {
        List<Node> cacheList = new ArrayList<Node>();
        List<Node> nodeList = new ArrayList<Node>();
        CameraClickListener listener;


        public NodeAdapter(List<Node> datas) {
            this.cacheList = datas;
            for (Node node : cacheList) {
                node.setOpen(false);
                if (node.getLevel() == 0) {
                    nodeList.add(node);
                }
            }
        }

        public void setListener(CameraClickListener listener){
            this.listener = listener;
        }
        @Override
        public NodeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new NodeHolder(LayoutInflater.from(parent.getContext())
                    .inflate(getResources().getIdentifier("node_item","layout",getActivity().getPackageName()), parent, false));
        }

        //获取将要展开的列表
        List<Node> getSubList(Node node) {
            List<Node> nodes = new ArrayList<Node>();
            for (Node temp : cacheList) {
                if (temp.getParentId() == node.getId()) {
                    temp.setOpen(false);
                    nodes.add(temp);
                }
            }
            return nodes;
        }

        //获取将要删除的列表项
        List<Node> getSubDelList(Node node, int clickPosition) {
            List<Node> nodes = new ArrayList<Node>();
            for (int i = clickPosition + 1; i < nodeList.size(); i++) {
                if (nodeList.get(i).getLevel() <= node.getLevel()) {
                    break;
                } else {
                    nodes.add(nodeList.get(i));
                }
            }
            return nodes;
        }


        public void itemClick(int clickPosition) {
            Node node = nodeList.get(clickPosition);
            if (node.getType() == Node.NODE_CAMERA) {
                if (listener != null)
                    listener.onCameraClick((CameraInfo) node.getRawData());
                return;
            }

            List<Node> tt;

            if (nodeList.get(clickPosition).isOpen()) {//关闭
                nodeList.get(clickPosition).setOpen(false);
                tt = getSubDelList(node, clickPosition);
                nodeList.removeAll(tt);
            } else {
                nodeList.get(clickPosition).setOpen(true);
                tt = getSubList(node);
                if (clickPosition + 1 == nodeList.size()) {
                    nodeList.addAll(tt);
                } else {
                    nodeList.addAll(clickPosition + 1, tt);
                }
            }
            notifyDataSetChanged();
        }

        @Override
        public void onBindViewHolder(NodeHolder holder, final int position) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemClick(position);
                }
            });
            Node node = nodeList.get(position);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();

            if (node.getType() == Node.NODE_UNIT) {
                params.setMargins(node.getLevel() * _MARGIN, params.topMargin, params.rightMargin, _MARGIN / 2);
                holder.title.setText(((ControlUnitInfo) node.getRawData()).getName());

                if (node.isOpen()) {
                    holder.node.setImageResource(getResources().getIdentifier("ic_keyboard_arrow_down_black_24dp","drawable",getActivity().getPackageName()));
                } else {
                    holder.node.setImageResource(getResources().getIdentifier("ic_keyboard_arrow_right_black_24dp","drawable",getActivity().getPackageName()));
                }

                holder.icon.setImageResource(getResources().getIdentifier("ic_desktop_windows_black_24dp","drawable",getActivity().getPackageName()));
            }

            if (node.getType() == Node.NODE_REGION) {
                params.setMargins(node.getLevel() * _MARGIN, params.topMargin, params.rightMargin, _MARGIN / 2);
                holder.title.setText(((RegionInfo) node.getRawData()).getName());

                if (node.isOpen()) {
                    holder.node.setImageResource(getResources().getIdentifier("ic_keyboard_arrow_down_black_24dp","drawable",getActivity().getPackageName()));
                } else {
                    holder.node.setImageResource(getResources().getIdentifier("ic_keyboard_arrow_right_black_24dp","drawable",getActivity().getPackageName()));
                }
                holder.icon.setImageResource(getResources().getIdentifier("ic_folder_special_black_24dp","drawable",getActivity().getPackageName()));

            }

            if (node.getType() == Node.NODE_CAMERA) {
                params.setMargins(node.getLevel() * _MARGIN + (int) (getResources().getDisplayMetrics().density * 24 + 0.5f),
                        params.topMargin, params.rightMargin, _MARGIN / 2);
                holder.title.setText(((CameraInfo) node.getRawData()).getName());

                holder.node.setImageDrawable(null);
                holder.icon.setImageResource(getResources().getIdentifier("ic_camera_alt_black_24dp","drawable",getActivity().getPackageName()));
            }

        }

        public int getItemCount() {
            return nodeList.size();
        }

        public class NodeHolder extends RecyclerView.ViewHolder {

            public ImageView node;
            public ImageView icon;
            public TextView title;

            public NodeHolder(View itemView) {
                super(itemView);
                node = (ImageView) itemView.findViewById(getResources().getIdentifier("node","id",getActivity().getPackageName()));
                icon = (ImageView) itemView.findViewById(getResources().getIdentifier("icon","id",getActivity().getPackageName()));
                title = (TextView) itemView.findViewById(getResources().getIdentifier("title","id",getActivity().getPackageName()));
            }
        }
    }
    interface CameraClickListener {
        void onCameraClick(CameraInfo info);
    }
    interface CameraCallback {
        void clickCamera();
    }
}
